<template>
        <div class="login">
            <div class="login__header">
                <p class='welcome'>欢迎使用“有借”</p>
                <p class='bind-text'>登录／注册</p>
            </div>
            <div class="login__form">
                <div class="login__item">
                    <span class="login__icon tel"></span>
                    <md-input text='手机号码' v-model='tel' type='tel' @change='telChangeHandle' @input='telChangeHandle("input")'></md-input>
                    <p class="login__validate" v-if='error_tel'>{{ error_tel }}</p>
                </div>
                <template v-if='mode == "login"'>
                    <div class="login__item">
                        <span class="login__icon password"></span>
                        <md-input text='登录密码' v-model='password' placeholder='6-18位数字字母组合' type='password'></md-input>
                        <p class="login__validate" v-if='error_password'>{{ error_password }}</p>
                        <p v-show='mode == "login"' class="login__forget button short pure" @click.stop='goForgetPassword'>忘记密码</p>
                    </div>
                </template>
                <template v-if='mode == "register"'>
                    <div class="login__item">
                        <span class="login__icon password"></span>
                        <md-input text='设置登录密码' v-model='password' placeholder='6-18位数字字母组合' type='password'></md-input>
                        <p class="login__validate" v-if='error_password'>{{ error_password }}</p>
                    </div>
                    <div class="login__item">
                        <span class="login__icon captcha"></span>
                        <md-input text='验证码' v-model='smsCode' type='tel'></md-input>
                        <p class="login__validate" v-if='error_smsCode'>{{ error_smsCode }}</p>
                        <div class="login__get-captcha" :class="{'sent': sent}">
                            <span class='get-code' @click='getSmscode'>获取验证码</span>
                            <span class='re-send'>{{ reSend }}</span>
                        </div>
                    </div>
                </template>
                <div class="login__button">
                    <div class="form__agreement">
                        <check-box v-model='agreementCheck'><span class='form__agreement-text'>已阅读并同意 <em @click.stop='showAgreement = true'>《有借用户使用协议》</em> </span></check-box>
                    </div>
                    <span class="button long" @click='next' :class='{disabled : !agreementCheck}'>{{title}}</span>
                </div>
            </div>

            <agreement
                :show='showAgreement'
                type='register'
                @close='showAgreement=false'></agreement>
        </div>
    </transition>
</template>

<script>
    import { Promise } from 'es6-promise'
    import mdInput from '../components/MDInput.vue'
    import agreement from '../components/Agreement.vue'
    import checkBox from '../components/CheckBox.vue'
    import  { mapGetters, mapActions }  from 'vuex'
    import { bindPhoneValidation } from '../validation/validation'
    import { allApi, loginApi, contactApi } from '../api/api'
    import { rules } from '../utils/utils'

    export default {
        components:{
            mdInput,
            checkBox,
            agreement
        },
        data(){
            return {
                showFooter:false,
                title:'下一步',
                showAgreement:false,
                agreementCheck:true,
                mode:'',
                error_tel:'',
                error_smsCode:'',
                error_password:'',
                passed:false,
                tel:'',
                telChange:false,
                smsCode:'',
                password:'',
                second:30,
                reSend:'30秒后重新发送',
                sent:false
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'setSessionId',
                'setNeedLogin',
                'setUserInfo',
                'setBizRole'
            ]),

            goRouter(name){
                this.$router.push({
                    name:name
                })
            },
            goForgetPassword(){
                this.$router.push({
                    name:'user-password-find-login',
                    query:{
                        mobile:this.tel
                    }
                })
            },
            getSmscode(){
                this.verification()
                if(!this.passed) return

                this.sent = true

                this.countDown()
                this.showLoading()
                loginApi.sendSms({
                    mobile:this.tel,
                    type:'REGISTER'
                })
                .then(result=>{
                    this.smsCode = result
                    this.hideLoading()
                })
                .catch(error => {
                    console.error(error)
                    this.sent = false
                    this.loading_count = false
                    this.hideLoading()
                })
            },
            countDown(){
                setTimeout(()=>{
                    if(this.second == 0){
                        this.sent = false
                        this.second = 30
                        return
                    }
                    this.second --
                    this.reSend = `${this.second}秒后重新发送`
                    this.countDown()
                },1000)
            },
            verification(type){
                // console.log(type)
                if(type == 'input'){
                    if(!rules.tel(this.tel)){
                        this.passed = false
                        this.mode = ''
                        this.title = '下一步'
                    }
                    else{
                        this.passed = true
                        this.error_tel = ''
                        this.error_smsCode = ''
                        this.error_password = ''
                    }
                    return
                }
                if(this.tel == ''){
                    this.error_tel = '手机号码不能为空'
                    this.passed = false
                    this.title = '下一步'
                    this.mode = ''
                    return
                }
                if(this.tel && !rules.tel(this.tel)){
                    this.error_tel = '请输入正确的手机号码'
                    this.passed = false
                    this.title = '下一步'
                    this.mode = ''
                    return
                }
                if(type == 'register'){
                    if(this.password == ''){
                        this.error_password = '请输入登录密码'
                        this.passed = false
                        return
                    }
                    if(this.password && !rules.password(this.password)){
                        this.error_password = '登录密码只能是6-18位字母数字组合'
                        this.passed = false
                        return
                    }
                    if(this.smsCode == ''){
                        this.error_smsCode = '请输入验证码'
                        this.passed = false
                        return
                    }
                }
                if(type == 'login'){
                    if(this.password == ''){
                        this.error_password = '请输入登录密码'
                        this.passed = false
                        return
                    }
                }
                this.passed = true
                this.error_tel = ''
                this.error_smsCode = ''
                this.error_password = ''
            },
            checkExist(mode){
                this.verification(mode)
                if(!this.passed) return

                this.showLoading()
                loginApi.checkExist({
                    mobile:this.tel
                })
                .then(result=>{
                    this.hideLoading()
                    this.showTel = false
                    this.setBizRole(result.bizRole)
                    let mode = result.exist
                    if(mode == false){
                        this.title = '注册'
                        this.mode = 'register'
                    }
                    else{
                        this.title = '登录'
                        this.mode = 'login'
                    }
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            addContact(result){
                return contactApi.add({
                    mobile:this.$route.query.mobile
                })
            },
            register(){
                this.verification('register')
                if(!this.passed) return


                allApi.onEvent({
                    eventType:'track_click',
                    eventName:'Signup',
                    eventDescr:'注册',
                    eventValue:JSON.stringify({
                        mobile:this.tel
                    }),
                })

                this.showLoading()
                loginApi.register({
                    preSessionId:this.$route.query.sessionId,
                    mobile:this.tel,
                    smsCode:this.smsCode,
                    loginPassword:this.password,
                })
                .then(result=>{
                    this.setSessionId(result.sessionId)
                    if(this.$route.query.mobile){
                        this.setUserInfo()
                        .then(this.addContact)
                        .then(result=>{
                            let name 
                            if(this.$route.query.loan == 'in'){ name = 'loan-in-detail-other' }
                            else{  name = 'loan-out-detail-other'  }

                            this.$ga.event({
                              eventCategory: 'register',
                              eventAction: 'jump',
                              eventLabel: '注册'
                            })
                            this.$router.push({
                                name:name,
                                params:{
                                    number:this.$route.query.number
                                }
                            })
                        })
                        .catch(error=>{
                            console.error(error)
                            let name 
                            if(this.$route.query.loan == 'in'){ name = 'loan-in-detail-other' }
                            else{  name = 'loan-out-detail-other'  }

                            this.$router.push({
                                name:name,
                                params:{
                                    number:this.$route.query.number
                                }
                            })
                        })

                    }
                    else{
                        this.setUserInfo()
                        .then(result=>{
                            this.$ga.event({
                              eventCategory: 'register',
                              eventAction: 'jump',
                              eventLabel: '注册'
                            })
                            this.goLoanIndex(result)
                        })
                        .catch(error=>{
                            console.error(error)
                            this.goLoanIndex()
                        })
                    }

                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            goUserIndex(result){
                this.hideLoading()
                this.setNeedLogin(false)
                if(result && !result.user.bizRole){
                    this.$router.push({
                        name:'id-select'
                    })
                    return
                }
                this.$router.replace({
                    name:'user-index'
                })
            },
            goLoanIndex(result){
                this.hideLoading()
                this.setNeedLogin(false)
                if(result && !result.user.bizRole){
                    this.$router.push({
                        name:'id-select'
                    })
                    return
                }
                if(this.$route.query.action == 'back'){
                    this.$router.back()
                    return
                }
                this.$router.replace({
                    name:'loan-in-index'
                })
            },
            login(){
                this.verification('login')
                if(!this.passed) return

                this.showLoading()
                loginApi.login({
                    preSessionId:this.$route.query.sessionId,
                    mobile:this.tel,
                    loginPassword:this.password,
                })
                .then(result=>{
                    this.setSessionId(result.sessionId)
                    if(this.$route.query.mobile){
                        this.setUserInfo()
                        .then(this.addContact)
                        .then(result=>{
                            let name 
                            if(this.$route.query.loan == 'in'){ name = 'loan-in-detail-other' }
                            else{  name = 'loan-out-detail-other'  }

                            this.$ga.event({
                              eventCategory: 'login',
                              eventAction: 'jump',
                              eventLabel: '登录'
                            })

                            this.$router.push({
                                name:name,
                                params:{
                                    number:this.$route.query.number
                                }
                            })
                        })
                        .catch(error=>{
                            console.error(error)
                            let name 
                            if(this.$route.query.loan == 'in'){ name = 'loan-in-detail-other' }
                            else{  name = 'loan-out-detail-other'  }

                            this.$router.push({
                                name:name,
                                params:{
                                    number:this.$route.query.number
                                }
                            })
                        })
                    }
                    else{
                        this.setUserInfo()
                        .then(result=>{
                            this.$ga.event({
                              eventCategory: 'login',
                              eventAction: 'jump',
                              eventLabel: '登录'
                            })
                            this.goUserIndex(result)
                        })
                        .catch(error=>{
                            console.error(error)
                            this.goUserIndex()
                        })
                        
                    }

                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            telChangeHandle(mode){
                // if(this.mode == '') return

                // if(mode == 'input'){
                //     this.verification('input')
                // }
                // else{
                //     this.verification()
                // }
                // if(!this.passed) return

                this.checkExist(mode)
            },
            next(){
                if(this.mode == ''){
                    this.checkExist()
                    return
                }

                if(this.mode == 'register'){
                    this.register()
                }

                if(this.mode == 'login'){
                    this.login()
                }

                
                // .then(result=>{
                //     this.smsCode = result
                //     this.hideLoading()
                // })
                // .catch(error => {
                //     console.error(error)
                //     this.sent = false
                //     this.loading_count = false
                //     this.hideLoading()
                // })
            }
        },
        created() {

        },
    }
</script>

<style lang="scss">
    @import "../sass/_variables";
    @import "../sass/_extends";
    @import "../sass/_mixins";

    
        .login{
            position: absolute;
            right: 0;
            left: 0;
            top: 0;
            bottom: 0;
            background-color: $backgroundColor;
            padding:24px;
        }
        .login__form{
            padding-top: 48px;
        }
        .login__header{
            padding-left: 40px;
            .welcome{
                @extend %font-caption;
            }
            .bind-text{
                @extend %font-title;
                color:$importColor;
            }
        }
        .login__item{
            display: flex;
            align-items: flex-start;
            padding-top: 68px;
            position: relative;
            &:first-child{
                padding-top: 0;
            }
        }
        .login__icon{
            display: block;
            font-size: 24px;
            margin-top: 5px;
            width: 24px;
            height: 24px;
            padding-right: 16px;
            background: url(../images/log_user.png) no-repeat center left;
            background-size: 16px 24px;
            &.captcha{
                background: url(../images/log_code.png) no-repeat center left;
                background-size: 20px 14px;
            }
            &.password{
                background: url(../images/log_password@3x.png) no-repeat center left;
                background-size: 24px 24px;
            }
        }
        .login__validate{
            position: absolute;
            bottom:-28px;
            left:40px;
            @extend %font-caption;
            color:$red;
        }
        .login__forget{
            position: absolute;
            bottom:0px;
            right:0;
            z-index:3;
        }
        .login__get-captcha{
            @extend %font-button;
            position: absolute;
            right:0;
            z-index:2;
            color:$orange;
            &:active{
                color:darken($orange,10%);
            }
            .get-code{
                display: block;
                padding:11px 5px 11px 11px;
            }
            .re-send{
                display: none;
                color:$sectionColor;
                padding:11px 5px 11px 11px;
            }
            &.sent{
                .get-code{
                    display: none;
                }
                .re-send{
                    display: block;
                }
            }
        }
        .login__button{
            padding-top: 58px;
            .form__agreement{
                padding-left:0;
            }
        }

</style>
